<template>
    <div
      :id="props.domId"
      class="editor-container"
    />
  </template>
  <script lang="ts" setup>
  import { onMounted, onUnmounted } from 'vue'
  import * as monaco from 'monaco-editor'
  
  let editor
  const props = defineProps({
    domId: {
      type: String,
      default: 'codeEditorDom'
    },
    language: {
      type: String,
      default: 'sql'
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    autoInit: {
      type: Boolean,
      default: true
    },
    minimap: {
      type: Boolean,
      default: false
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    }
  })
  
  onMounted(() => {
    if (props.autoInit) {
      init()
    }
  })
  
  onUnmounted(() => {
    editor.dispose()
  })
  
  function init() {
    // 使用 - 创建 monacoEditor 对象
    const defaultOptions: any = {
      // theme, // 主题
      value: '', // 默认显示的值
      language: props.language, // 语言
      folding: true, // 是否折叠
      minimap: {
        // 关闭小地图
        enabled: false
      },
      wordWrap: 'on',
      wrappingIndent: 'indent',
      foldingHighlight: true, // 折叠等高线
      foldingStrategy: 'indentation', // 折叠方式  auto | indentation
      showFoldingControls: 'always', // 是否一直显示折叠 always | mouseover
      disableLayerHinting: true, // 等宽优化
      emptySelectionClipboard: false, // 空选择剪切板
      selectionClipboard: true, // 选择剪切板
      automaticLayout: true, // 自动布局
      // overviewRulerBorder: true, // 不要滚动条的边框
      codeLens: true, // 代码镜头
      scrollBeyondLastLine: true, // 滚动完最后一行后再滚动一屏幕
      colorDecorators: true, // 颜色装饰器
      accessibilitySupport: 'on', // 辅助功能支持  "auto" | "off" | "on"
      lineNumbers: 'on', // 行号 取值： "on" | "off" | "relative" | "interval" | function
      lineNumbersMinChars: 5, // 行号最小字符   number
      lineHeight:24, // 行高
      fontSize: 16, // 字体大小
      // enableSplitViewResizing: 'on',
      readOnly: props.readOnly, // 是否只读  取值 true | false
      renderIndentGuides: false,
      fixedOverflowWidgets: true,
      quickSuggestions: true,
      acceptSuggestionOnEnter: 'on',
      theme: 'vs',
      formatOnPaste: true // 粘贴时自动格式化
    }
  
    editor = monaco.editor.create(
      document.querySelector('#' + props.domId) as HTMLElement,
      defaultOptions
    )
  }
  
  function set(val: string) {
    editor.setValue(val)
  }
  
  function get(val: string) {
    return editor.getValue()
  }
  
  function format() {
    if (props.readOnly) {
      editor.updateOptions({ readOnly: false })
    }
    editor
      .getAction('editor.action.formatDocument')
      ?.run()
      .then(() => {
        if (props.readOnly) {
          editor.updateOptions({ readOnly: true })
        }
      })
  }
  
  defineExpose({
    init,
    set,
    get,
    format
  })
  </script>
  <style>
  .editor-container {
    /* border: 1px solid #ccc; */
    width: 100%;
    height: 100%;
  }
  </style>
  